<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="10" :lg="11" :md="12" :sm="24">
            <a-form-item :label="$t('使用时间')">
              <j-date
                :show-time="{ defaultValue: moment('00:00:00', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss" 
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择开始时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_begin"
              ></j-date>
              <span class="query-group-split-cust"></span>
              <j-date
                :show-time="{ defaultValue: moment('23:59:59', 'HH:mm:ss') }"
                valueFormat="YYYY-MM-DD HH:mm:ss" 
                dateFormat="YYYY-MM-DD HH:mm:ss"
                :placeholder="$t('请选择结束时间')"
                class="query-group-cust"
                v-model="queryParam.createTime_end"
              ></j-date>
            </a-form-item>
          </a-col>
          <a-col :xl="5" :lg="6" :md="7" :sm="24">
            <a-form-item :label="$t('会员信息')">
              <a-input :placeholder="$t('请输入手机号/卡号/姓名')" v-model="queryParam.memberInfo"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('券信息')">
                <a-input :placeholder="$t('请输入优惠券券号/名称')" v-model="queryParam.couponInfo"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('订单号')">
                <a-input :placeholder="$t('请输入订单号')" v-model="queryParam.orderId"></a-input>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('业务渠道')">
                <a-select v-model="queryParam.deviceType">
                  <a-select-option :key="index" v-for="(item, index) in typeList" :value="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="6" :md="7" :sm="24">
              <a-form-item :label="$t('操作员')">
                <a-select v-model="queryParam.createBy">
                  <a-select-option :key="index" v-for="(item, index) in userList" :value="item.value">{{
                    item.text
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :xl="7" :lg="8" :md="9" :sm="24">
              <a-form-item :label="$t('设备名称(编码)')">
                <a-select show-search :filter-option="false" @search="handleSearch" v-model="queryParam.deviceId">
                  <a-select-option :value="item.id" :key="index" v-for="(item, index) in deviceList">
                    <span>{{ item.name }}</span>
                    <span v-if="item.name != $t('全部')">({{ item.id }})</span>
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">{{$t('查询')}}</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">{{$t('重置')}}</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? $t('收起') : $t('展开') }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
              <a-button
              v-has="'BisMemberCouponUseController:export'"
                type="primary"
                icon="download"
                style="margin-left: 8px"
                @click="handleExportXls($t('优惠券使用记录'))"
                >{{$t('导出')}}</a-button
              >
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{ x: true }"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :customHeaderRow="customHeaderRow"
        :customRow="customRow"
        class="j-table-force-nowrap"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{$t('无图片')}}</span>
          <img
            v-else
            :src="getImgView(text)"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">{{$t('无文件')}}</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            {{$t('下载')}}
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">{{$t('编辑')}}</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">{{$t('更多')}} <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">{{$t('详情')}}</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm :title="$t('确定删除吗?')" @confirm="() => handleDelete(record.id)">
                  <a>{{$t('删除')}}</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
        <template slot="footer">
          <div style="font-weight: bold">
            <span style="margin-left: 15px;margin-right: 5px">{{$t('面额')}}：</span><span>{{ value.toFixed(2) }}</span>
            <span style="margin-left: 15px;margin-right: 5px">{{$t('抵扣金额')}}：</span><span>{{ full.toFixed(2) }}</span>
          </div>
        </template>
      </a-table>
    </div>

    <bis-member-coupon-use-modal ref="modalForm" @ok="modalFormOk"></bis-member-coupon-use-modal>
  </a-card>
</template>

<script>
import moment from 'moment'
import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import { getAction, downFile } from '@/api/manage'
import BisMemberCouponUseModal from './modules/BisMemberCouponUseModal'

export default {
  name: 'BisMemberCouponUseList',
  mixins: [mixinDevice],
  components: {
    BisMemberCouponUseModal,
  },
  data() {
    return {
      description: '优惠券使用记录管理页面',
      moment,
      // 表头
      columns: [
        {
          title: this.$t('使用时间'),
          align: 'center',
          dataIndex: 'createTime',
        },
        {
          title: this.$t('订单号'),
          align: 'center',
          dataIndex: 'orderId',
        },
        {
          title: this.$t('手机号'),
          align: 'center',
          dataIndex: 'memberPhone',
        },
        {
          title: this.$t('卡号'),
          align: 'center',
          dataIndex: 'chipNo',
        },
        {
          title: this.$t('姓名'),
          align: 'center',
          dataIndex: 'memberName',
        },
        {
          title: this.$t('券号'),
          align: 'center',
          dataIndex: 'memberCouponId',
        },
        {
          title: this.$t('券名称'),
          align: 'center',
          dataIndex: 'couponName',
        },
        {
          title: this.$t('面额'),
          align: 'center',
          dataIndex: 'couponValue',
          customRender: (text, record) => {
            return record.couponValue.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('抵扣金额'),
          align: 'center',
          dataIndex: 'couponDiscount',
          customRender: (text, record) => {
            return record.couponDiscount.toFixed(2)
          },
          customCell: function () {
            return {
              style: {
                textAlign: 'right',
              },
            }
          },
        },
        {
          title: this.$t('业务渠道'),
          align: 'center',
          dataIndex: 'deviceType_dictText',
        },
        {
          title: this.$t('设备名称(编码)'),
          align: 'center',
          dataIndex: 'deviceId_dictText',
          customRender: function (text, record) {
            if(text){
              return record.deviceId_dictText + '（' + record.deviceId + '）'
            }else{
              return ''
            }
          },
        },
        {
          title: this.$t('操作员'),
          align: 'center',
          dataIndex: 'createBy_dictText',
        },
      ],
      url: {
        list: '/member/bisMemberCouponUse/list',
        delete: '/member/bisMemberCouponUse/delete',
        deleteBatch: '/member/bisMemberCouponUse/deleteBatch',
        exportXlsUrl: '/member/bisMemberCouponUse/exportXls',
        importExcelUrl: 'member/bisMemberCouponUse/importExcel',
      },
      dictOptions: {},
      toggleSearchStatus: true,
      typeList: [],
      deviceList: [],
      userList: [],
      queryParam: {
        column: 'createTime',
        order: 'desc',
        createTime_begin: '',
        createTime_end: '',
        memberInfo: '',
        couponInfo: '',
        orderId: '',
        deviceType: '',
        createBy: '',
        deviceId: '',
      },
      dataSource: [],
      loading: false,
      value: 0,
      full: 0,
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('sum-total',{total:total})
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
        onShowSizeChange: (current, pageSize) => this.handleSizeChange(current, pageSize),
      },
      selectedRowIndex: []
    }
  },
  created() {
    this.initDictConfig()
    this.loadData(1)
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    customHeaderRow(){
      return {
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word'
        }
      }
    },
    customRow(record, i) {
      return {
        on: {
          click: () => {
            let x = this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i})
            if( x == -1 ){
              this.selectedRowIndex.push('a'+this.ipagination.current+''+i)
            }else{
              this.selectedRowIndex.splice(x, 1)
            }
          }
        },
        style: {
          whiteSpace: 'break-spaces',
          wordBreak: 'break-word',
          overflowWrap: 'break-word',
          backgroundColor: this.selectedRowIndex.findIndex(r=>{return r=='a'+this.ipagination.current+''+i}) > -1 ? '#FFECE6' : ''
        }
      }
    },
    initDictConfig() {
      initDictOptions('bis_device_info.type').then((res) => {
        this.typeList = res.result
        this.typeList.unshift({ value: '', text: this.$t('全部') })
      })
      initDictOptions('sys_user,realname,realname').then((res) => {
        this.userList = res.result
        this.userList.unshift({ value: '', text: this.$t('全部') })
      })
      this.handleSearch('')
    },
    handleSearch(value) {
      let query={}
      if(value){
        query.deviceInfo= value
      }
      getAction('/device/bisDeviceInfo/list',query).then((res) => {
        if (res.success) {
          this.deviceList = res.result.records
          this.deviceList.unshift({ id: '', name: this.$t('全部') })
        }
      })
    },
    searchReset() {
      this.queryParam = {
        column: 'createTime',
        order: 'desc',
        createTime_begin: '',
        createTime_end: '',
        memberInfo: '',
        couponInfo: '',
        orderId: '',
        deviceType: '',
        createBy: '',
        deviceId: '',
      }
      this.selectedRowIndex = []
      this.loadData(1)
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    searchQuery(){
      this.selectedRowIndex = []
      this.loadData(1);
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error(this.$t('请设置url.list属性'))
        return
      }
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.queryParam
      params.pageNo=this.ipagination.current
      params.pageSize=this.ipagination.pageSize
      this.loading = true
      getAction(this.url.list, params)
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records
            this.getTotal()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
              this.selectedRowIndex = []
            }
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    getTotal() {
      getAction('/member/bisMemberCouponUse/total', this.queryParam).then((res) => {
        if (res.success) {
          this.value = res.result.records[0].couponValue
          this.full = res.result.records[0].couponDiscount
        }
      })
    },
    modalFormOk() {
      this.loadData(1)
    },
    handleTableChange(pagination, filters, sorter) {
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleExportXls(fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = this.$t('导出文件')
      }
      let param = this.queryParam
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      if (this.isNoPageTotal) {
        param.pageSize = 99999999
      }
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning(this.$t('文件下载失败'))
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>